home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / threading.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2005-10-18  |  20KB  |  742 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. """Thread module emulating a subset of Java's threading model."""
  5. import sys as _sys
  6.  
  7. try:
  8.     import thread
  9. except ImportError:
  10.     del _sys.modules[__name__]
  11.     raise 
  12.  
  13. from time import time as _time, sleep as _sleep
  14. from traceback import format_exc as _format_exc
  15. from collections import deque
  16. __all__ = [
  17.     'activeCount',
  18.     'Condition',
  19.     'currentThread',
  20.     'enumerate',
  21.     'Event',
  22.     'Lock',
  23.     'RLock',
  24.     'Semaphore',
  25.     'BoundedSemaphore',
  26.     'Thread',
  27.     'Timer',
  28.     'setprofile',
  29.     'settrace',
  30.     'local']
  31. _start_new_thread = thread.start_new_thread
  32. _allocate_lock = thread.allocate_lock
  33. _get_ident = thread.get_ident
  34. ThreadError = thread.error
  35. del thread
  36. _VERBOSE = False
  37.  
  38. class _Verbose(object):
  39.     
  40.     def __init__(self, verbose = None):
  41.         pass
  42.  
  43.     
  44.     def _note(self, *args):
  45.         pass
  46.  
  47.  
  48. _profile_hook = None
  49. _trace_hook = None
  50.  
  51. def setprofile(func):
  52.     global _profile_hook
  53.     _profile_hook = func
  54.  
  55.  
  56. def settrace(func):
  57.     global _trace_hook
  58.     _trace_hook = func
  59.  
  60. Lock = _allocate_lock
  61.  
  62. def RLock(*args, **kwargs):
  63.     return _RLock(*args, **kwargs)
  64.  
  65.  
  66. class _RLock(_Verbose):
  67.     
  68.     def __init__(self, verbose = None):
  69.         _Verbose.__init__(self, verbose)
  70.         self._RLock__block = _allocate_lock()
  71.         self._RLock__owner = None
  72.         self._RLock__count = 0
  73.  
  74.     
  75.     def __repr__(self):
  76.         if self._RLock__owner:
  77.             pass
  78.         return '<%s(%s, %d)>' % (self.__class__.__name__, self._RLock__owner.getName(), self._RLock__count)
  79.  
  80.     
  81.     def acquire(self, blocking = 1):
  82.         me = currentThread()
  83.         if self._RLock__owner is me:
  84.             self._RLock__count = self._RLock__count + 1
  85.             return 1
  86.         
  87.         rc = self._RLock__block.acquire(blocking)
  88.         if rc:
  89.             self._RLock__owner = me
  90.             self._RLock__count = 1
  91.         
  92.         return rc
  93.  
  94.     
  95.     def release(self):
  96.         me = currentThread()
  97.         self._RLock__count = count = self._RLock__count - 1
  98.         if not count:
  99.             self._RLock__owner = None
  100.             self._RLock__block.release()
  101.         
  102.  
  103.     
  104.     def _acquire_restore(self, .2):
  105.         (count, owner) = .2
  106.         self._RLock__block.acquire()
  107.         self._RLock__count = count
  108.         self._RLock__owner = owner
  109.  
  110.     
  111.     def _release_save(self):
  112.         count = self._RLock__count
  113.         self._RLock__count = 0
  114.         owner = self._RLock__owner
  115.         self._RLock__owner = None
  116.         self._RLock__block.release()
  117.         return (count, owner)
  118.  
  119.     
  120.     def _is_owned(self):
  121.         return self._RLock__owner is currentThread()
  122.  
  123.  
  124.  
  125. def Condition(*args, **kwargs):
  126.     return _Condition(*args, **kwargs)
  127.  
  128.  
  129. class _Condition(_Verbose):
  130.     
  131.     def __init__(self, lock = None, verbose = None):
  132.         _Verbose.__init__(self, verbose)
  133.         if lock is None:
  134.             lock = RLock()
  135.         
  136.         self._Condition__lock = lock
  137.         self.acquire = lock.acquire
  138.         self.release = lock.release
  139.         
  140.         try:
  141.             self._release_save = lock._release_save
  142.         except AttributeError:
  143.             pass
  144.  
  145.         
  146.         try:
  147.             self._acquire_restore = lock._acquire_restore
  148.         except AttributeError:
  149.             pass
  150.  
  151.         
  152.         try:
  153.             self._is_owned = lock._is_owned
  154.         except AttributeError:
  155.             pass
  156.  
  157.         self._Condition__waiters = []
  158.  
  159.     
  160.     def __repr__(self):
  161.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  162.  
  163.     
  164.     def _release_save(self):
  165.         self._Condition__lock.release()
  166.  
  167.     
  168.     def _acquire_restore(self, x):
  169.         self._Condition__lock.acquire()
  170.  
  171.     
  172.     def _is_owned(self):
  173.         if self._Condition__lock.acquire(0):
  174.             self._Condition__lock.release()
  175.             return False
  176.         else:
  177.             return True
  178.  
  179.     
  180.     def wait(self, timeout = None):
  181.         waiter = _allocate_lock()
  182.         waiter.acquire()
  183.         self._Condition__waiters.append(waiter)
  184.         saved_state = self._release_save()
  185.         
  186.         try:
  187.             if timeout is None:
  188.                 waiter.acquire()
  189.             else:
  190.                 endtime = _time() + timeout
  191.                 delay = 0.00050000000000000001
  192.                 while True:
  193.                     gotit = waiter.acquire(0)
  194.                     if gotit:
  195.                         break
  196.                     
  197.                     remaining = endtime - _time()
  198.                     if remaining <= 0:
  199.                         break
  200.                     
  201.                     delay = min(delay * 2, remaining, 0.050000000000000003)
  202.                     _sleep(delay)
  203.                 if not gotit:
  204.                     
  205.                     try:
  206.                         self._Condition__waiters.remove(waiter)
  207.                     except ValueError:
  208.                         pass
  209.                     except:
  210.                         None<EXCEPTION MATCH>ValueError
  211.                     
  212.  
  213.                 None<EXCEPTION MATCH>ValueError
  214.         finally:
  215.             self._acquire_restore(saved_state)
  216.  
  217.  
  218.     
  219.     def notify(self, n = 1):
  220.         _Condition__waiters = self._Condition__waiters
  221.         waiters = _Condition__waiters[:n]
  222.         if not waiters:
  223.             return None
  224.         
  225.         if not n != 1 or 's':
  226.             pass
  227.         self._note('%s.notify(): notifying %d waiter%s', self, n, '')
  228.         for waiter in waiters:
  229.             waiter.release()
  230.             
  231.             try:
  232.                 _Condition__waiters.remove(waiter)
  233.             continue
  234.             except ValueError:
  235.                 continue
  236.             
  237.  
  238.         
  239.  
  240.     
  241.     def notifyAll(self):
  242.         self.notify(len(self._Condition__waiters))
  243.  
  244.  
  245.  
  246. def Semaphore(*args, **kwargs):
  247.     return _Semaphore(*args, **kwargs)
  248.  
  249.  
  250. class _Semaphore(_Verbose):
  251.     
  252.     def __init__(self, value = 1, verbose = None):
  253.         _Verbose.__init__(self, verbose)
  254.         self._Semaphore__cond = Condition(Lock())
  255.         self._Semaphore__value = value
  256.  
  257.     
  258.     def acquire(self, blocking = 1):
  259.         rc = False
  260.         self._Semaphore__cond.acquire()
  261.         while self._Semaphore__value == 0:
  262.             if not blocking:
  263.                 break
  264.             
  265.             self._Semaphore__cond.wait()
  266.         self._Semaphore__value = self._Semaphore__value - 1
  267.         rc = True
  268.         self._Semaphore__cond.release()
  269.         return rc
  270.  
  271.     
  272.     def release(self):
  273.         self._Semaphore__cond.acquire()
  274.         self._Semaphore__value = self._Semaphore__value + 1
  275.         self._Semaphore__cond.notify()
  276.         self._Semaphore__cond.release()
  277.  
  278.  
  279.  
  280. def BoundedSemaphore(*args, **kwargs):
  281.     return _BoundedSemaphore(*args, **kwargs)
  282.  
  283.  
  284. class _BoundedSemaphore(_Semaphore):
  285.     '''Semaphore that checks that # releases is <= # acquires'''
  286.     
  287.     def __init__(self, value = 1, verbose = None):
  288.         _Semaphore.__init__(self, value, verbose)
  289.         self._initial_value = value
  290.  
  291.     
  292.     def release(self):
  293.         if self._Semaphore__value >= self._initial_value:
  294.             raise ValueError, 'Semaphore released too many times'
  295.         
  296.         return _Semaphore.release(self)
  297.  
  298.  
  299.  
  300. def Event(*args, **kwargs):
  301.     return _Event(*args, **kwargs)
  302.  
  303.  
  304. class _Event(_Verbose):
  305.     
  306.     def __init__(self, verbose = None):
  307.         _Verbose.__init__(self, verbose)
  308.         self._Event__cond = Condition(Lock())
  309.         self._Event__flag = False
  310.  
  311.     
  312.     def isSet(self):
  313.         return self._Event__flag
  314.  
  315.     
  316.     def set(self):
  317.         self._Event__cond.acquire()
  318.         
  319.         try:
  320.             self._Event__flag = True
  321.             self._Event__cond.notifyAll()
  322.         finally:
  323.             self._Event__cond.release()
  324.  
  325.  
  326.     
  327.     def clear(self):
  328.         self._Event__cond.acquire()
  329.         
  330.         try:
  331.             self._Event__flag = False
  332.         finally:
  333.             self._Event__cond.release()
  334.  
  335.  
  336.     
  337.     def wait(self, timeout = None):
  338.         self._Event__cond.acquire()
  339.         
  340.         try:
  341.             if not self._Event__flag:
  342.                 self._Event__cond.wait(timeout)
  343.         finally:
  344.             self._Event__cond.release()
  345.  
  346.  
  347.  
  348. _counter = 0
  349.  
  350. def _newname(template = 'Thread-%d'):
  351.     global _counter
  352.     _counter = _counter + 1
  353.     return template % _counter
  354.  
  355. _active_limbo_lock = _allocate_lock()
  356. _active = { }
  357. _limbo = { }
  358.  
  359. class Thread(_Verbose):
  360.     __initialized = False
  361.     __exc_info = _sys.exc_info
  362.     
  363.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = { }, verbose = None):
  364.         _Verbose.__init__(self, verbose)
  365.         self._Thread__target = target
  366.         if not name:
  367.             pass
  368.         self._Thread__name = str(_newname())
  369.         self._Thread__args = args
  370.         self._Thread__kwargs = kwargs
  371.         self._Thread__daemonic = self._set_daemon()
  372.         self._Thread__started = False
  373.         self._Thread__stopped = False
  374.         self._Thread__block = Condition(Lock())
  375.         self._Thread__initialized = True
  376.         self._Thread__stderr = _sys.stderr
  377.  
  378.     
  379.     def _set_daemon(self):
  380.         return currentThread().isDaemon()
  381.  
  382.     
  383.     def __repr__(self):
  384.         status = 'initial'
  385.         if self._Thread__started:
  386.             status = 'started'
  387.         
  388.         if self._Thread__stopped:
  389.             status = 'stopped'
  390.         
  391.         if self._Thread__daemonic:
  392.             status = status + ' daemon'
  393.         
  394.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  395.  
  396.     
  397.     def start(self):
  398.         _active_limbo_lock.acquire()
  399.         _limbo[self] = self
  400.         _active_limbo_lock.release()
  401.         _start_new_thread(self._Thread__bootstrap, ())
  402.         self._Thread__started = True
  403.         _sleep(9.9999999999999995e-07)
  404.  
  405.     
  406.     def run(self):
  407.         if self._Thread__target:
  408.             self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
  409.         
  410.  
  411.     
  412.     def __bootstrap(self):
  413.         
  414.         try:
  415.             self._Thread__started = True
  416.             _active_limbo_lock.acquire()
  417.             _active[_get_ident()] = self
  418.             del _limbo[self]
  419.             _active_limbo_lock.release()
  420.             if _trace_hook:
  421.                 self._note('%s.__bootstrap(): registering trace hook', self)
  422.                 _sys.settrace(_trace_hook)
  423.             
  424.             if _profile_hook:
  425.                 self._note('%s.__bootstrap(): registering profile hook', self)
  426.                 _sys.setprofile(_profile_hook)
  427.             
  428.             
  429.             try:
  430.                 self.run()
  431.             except SystemExit:
  432.                 pass
  433.             except:
  434.                 if _sys:
  435.                     _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.getName(), _format_exc()))
  436.                 else:
  437.                     (exc_type, exc_value, exc_tb) = self._Thread__exc_info()
  438.                     
  439.                     try:
  440.                         print >>self._Thread__stderr, 'Exception in thread ' + self.getName() + ' (most likely raised during interpreter shutdown):'
  441.                         print >>self._Thread__stderr, 'Traceback (most recent call last):'
  442.                         while exc_tb:
  443.                             print >>self._Thread__stderr, '  File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)
  444.                             exc_tb = exc_tb.tb_next
  445.                         print >>self._Thread__stderr, '%s: %s' % (exc_type, exc_value)
  446.                     finally:
  447.                         del exc_type
  448.                         del exc_value
  449.                         del exc_tb
  450.  
  451.  
  452.         finally:
  453.             self._Thread__stop()
  454.             
  455.             try:
  456.                 self._Thread__delete()
  457.             except:
  458.                 pass
  459.  
  460.  
  461.  
  462.     
  463.     def __stop(self):
  464.         self._Thread__block.acquire()
  465.         self._Thread__stopped = True
  466.         self._Thread__block.notifyAll()
  467.         self._Thread__block.release()
  468.  
  469.     
  470.     def __delete(self):
  471.         '''Remove current thread from the dict of currently running threads.'''
  472.         _active_limbo_lock.acquire()
  473.         
  474.         try:
  475.             del _active[_get_ident()]
  476.         except KeyError:
  477.             if 'dummy_threading' not in _sys.modules:
  478.                 raise 
  479.             
  480.         except:
  481.             'dummy_threading' not in _sys.modules
  482.         finally:
  483.             _active_limbo_lock.release()
  484.  
  485.  
  486.     
  487.     def join(self, timeout = None):
  488.         self._Thread__block.acquire()
  489.         if timeout is None:
  490.             while not self._Thread__stopped:
  491.                 self._Thread__block.wait()
  492.         else:
  493.             deadline = _time() + timeout
  494.             while not self._Thread__stopped:
  495.                 delay = deadline - _time()
  496.                 if delay <= 0:
  497.                     break
  498.                 
  499.                 self._Thread__block.wait(delay)
  500.         self._Thread__block.release()
  501.  
  502.     
  503.     def getName(self):
  504.         return self._Thread__name
  505.  
  506.     
  507.     def setName(self, name):
  508.         self._Thread__name = str(name)
  509.  
  510.     
  511.     def isAlive(self):
  512.         if self._Thread__started:
  513.             pass
  514.         return not (self._Thread__stopped)
  515.  
  516.     
  517.     def isDaemon(self):
  518.         return self._Thread__daemonic
  519.  
  520.     
  521.     def setDaemon(self, daemonic):
  522.         self._Thread__daemonic = daemonic
  523.  
  524.  
  525.  
  526. def Timer(*args, **kwargs):
  527.     return _Timer(*args, **kwargs)
  528.  
  529.  
  530. class _Timer(Thread):
  531.     """Call a function after a specified number of seconds:
  532.  
  533.     t = Timer(30.0, f, args=[], kwargs={})
  534.     t.start()
  535.     t.cancel() # stop the timer's action if it's still waiting
  536.     """
  537.     
  538.     def __init__(self, interval, function, args = [], kwargs = { }):
  539.         Thread.__init__(self)
  540.         self.interval = interval
  541.         self.function = function
  542.         self.args = args
  543.         self.kwargs = kwargs
  544.         self.finished = Event()
  545.  
  546.     
  547.     def cancel(self):
  548.         """Stop the timer if it hasn't finished yet"""
  549.         self.finished.set()
  550.  
  551.     
  552.     def run(self):
  553.         self.finished.wait(self.interval)
  554.         if not self.finished.isSet():
  555.             self.function(*self.args, **self.kwargs)
  556.         
  557.         self.finished.set()
  558.  
  559.  
  560.  
  561. class _MainThread(Thread):
  562.     
  563.     def __init__(self):
  564.         Thread.__init__(self, name = 'MainThread')
  565.         self._Thread__started = True
  566.         _active_limbo_lock.acquire()
  567.         _active[_get_ident()] = self
  568.         _active_limbo_lock.release()
  569.         import atexit as atexit
  570.         atexit.register(self._MainThread__exitfunc)
  571.  
  572.     
  573.     def _set_daemon(self):
  574.         return False
  575.  
  576.     
  577.     def _MainThread__exitfunc(self):
  578.         self._Thread__stop()
  579.         t = _pickSomeNonDaemonThread()
  580.         if t:
  581.             pass
  582.         
  583.         while t:
  584.             t.join()
  585.             t = _pickSomeNonDaemonThread()
  586.         self._Thread__delete()
  587.  
  588.  
  589.  
  590. def _pickSomeNonDaemonThread():
  591.     for t in enumerate():
  592.         if not t.isDaemon() and t.isAlive():
  593.             return t
  594.             continue
  595.     
  596.  
  597.  
  598. class _DummyThread(Thread):
  599.     
  600.     def __init__(self):
  601.         Thread.__init__(self, name = _newname('Dummy-%d'))
  602.         self._Thread__started = True
  603.         _active_limbo_lock.acquire()
  604.         _active[_get_ident()] = self
  605.         _active_limbo_lock.release()
  606.  
  607.     
  608.     def _set_daemon(self):
  609.         return True
  610.  
  611.     
  612.     def join(self, timeout = None):
  613.         pass
  614.  
  615.  
  616.  
  617. def currentThread():
  618.     
  619.     try:
  620.         return _active[_get_ident()]
  621.     except KeyError:
  622.         return _DummyThread()
  623.  
  624.  
  625.  
  626. def activeCount():
  627.     _active_limbo_lock.acquire()
  628.     count = len(_active) + len(_limbo)
  629.     _active_limbo_lock.release()
  630.     return count
  631.  
  632.  
  633. def enumerate():
  634.     _active_limbo_lock.acquire()
  635.     active = _active.values() + _limbo.values()
  636.     _active_limbo_lock.release()
  637.     return active
  638.  
  639. _MainThread()
  640.  
  641. try:
  642.     from thread import _local as local
  643. except ImportError:
  644.     from _threading_local import local
  645.  
  646.  
  647. def _test():
  648.     
  649.     class BoundedQueue(_Verbose):
  650.         
  651.         def __init__(self, limit):
  652.             _Verbose.__init__(self)
  653.             self.mon = RLock()
  654.             self.rc = Condition(self.mon)
  655.             self.wc = Condition(self.mon)
  656.             self.limit = limit
  657.             self.queue = deque()
  658.  
  659.         
  660.         def put(self, item):
  661.             self.mon.acquire()
  662.             while len(self.queue) >= self.limit:
  663.                 self._note('put(%s): queue full', item)
  664.                 self.wc.wait()
  665.             self.queue.append(item)
  666.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  667.             self.rc.notify()
  668.             self.mon.release()
  669.  
  670.         
  671.         def get(self):
  672.             self.mon.acquire()
  673.             while not self.queue:
  674.                 self._note('get(): queue empty')
  675.                 self.rc.wait()
  676.             item = self.queue.popleft()
  677.             self._note('get(): got %s, %d left', item, len(self.queue))
  678.             self.wc.notify()
  679.             self.mon.release()
  680.             return item
  681.  
  682.  
  683.     
  684.     class ProducerThread(Thread):
  685.         
  686.         def __init__(self, queue, quota):
  687.             Thread.__init__(self, name = 'Producer')
  688.             self.queue = queue
  689.             self.quota = quota
  690.  
  691.         
  692.         def run(self):
  693.             random = random
  694.             import random
  695.             counter = 0
  696.             while counter < self.quota:
  697.                 counter = counter + 1
  698.                 self.queue.put('%s.%d' % (self.getName(), counter))
  699.                 _sleep(random() * 1.0000000000000001e-05)
  700.  
  701.  
  702.     
  703.     class ConsumerThread(Thread):
  704.         
  705.         def __init__(self, queue, count):
  706.             Thread.__init__(self, name = 'Consumer')
  707.             self.queue = queue
  708.             self.count = count
  709.  
  710.         
  711.         def run(self):
  712.             while self.count > 0:
  713.                 item = self.queue.get()
  714.                 print item
  715.                 self.count = self.count - 1
  716.  
  717.  
  718.     NP = 3
  719.     QL = 4
  720.     NI = 5
  721.     Q = BoundedQueue(QL)
  722.     P = []
  723.     for i in range(NP):
  724.         t = ProducerThread(Q, NI)
  725.         t.setName('Producer-%d' % (i + 1))
  726.         P.append(t)
  727.     
  728.     C = ConsumerThread(Q, NI * NP)
  729.     for t in P:
  730.         t.start()
  731.         _sleep(9.9999999999999995e-07)
  732.     
  733.     C.start()
  734.     for t in P:
  735.         t.join()
  736.     
  737.     C.join()
  738.  
  739. if __name__ == '__main__':
  740.     _test()
  741.  
  742.